package com.example.controller;

import com.example.entity.Pet;
import com.example.entity.User;
import com.example.service.PetService;
import com.example.service.impl.PetServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

// 声明该类为Spring MVC的控制器，处理与宠物相关的请求
@Controller
// 定义该控制器处理的请求路径前缀为 /pet
@RequestMapping("/pet")
public class PetController {
    // 自动注入PetService实例，用于处理宠物业务逻辑
    @Autowired
    private PetService petService;

    /**
     * 获取指定用户的宠物列表
     * @param user_id 用户ID
     * @param model 用于向视图传递数据的模型
     * @return 视图名称，指向显示宠物列表的页面
     */
    @GetMapping("/list")
    public String petList(@Param("user_id") Integer user_id, Model model) {
        // 调用PetService的petList方法获取指定用户的宠物列表
        List<Pet> petList = petService.petList(user_id);
        System.out.println("petList" + petList);
        // 将宠物列表添加到模型中，供视图使用
        model.addAttribute("petList", petList);
        // 返回视图名称，跳转到显示宠物列表的页面
        return "/user/pet";
    }

    @RequestMapping("/add")
    public String addPet(
            @RequestParam("petName") String name,
            @RequestParam("petType") String type,
            @RequestParam("petBreed") String breed,
            @RequestParam(value = "petAge", required = false) Integer age, // 改为 Integer
            @RequestParam("petWeight") double weight,
            @RequestParam("petPhotoUrl") String photoUrl,
            @RequestParam("petHealthStatus") String healthStatus,
            HttpSession session,
            Model model
    ) {
        // 从会话中获取当前登录的用户信息
        User user = (User) session.getAttribute("login_user");
        // 创建Pet对象
        Pet pet = new Pet();
        pet.setUser_id(user.getUser_id());
        pet.setName(name);
        pet.setType(type);
        pet.setBreed(breed);

        pet.setAge(age);
        pet.setWeight(weight);
        pet.setPhoto_url(photoUrl);
        pet.setHealth_status(healthStatus);
        petService.addPet(pet);
        System.out.println("pet" + pet);
        List<Pet> petList = petService.petList(user.getUser_id());
        System.out.println("petList" + petList);
        model.addAttribute("petList", petList);
        return "/user/pet";
    }
}